package com.dlwx.firefighting.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dlwx.firefighting.R;
import com.dlwx.firefighting.adapter.OrderDetailAdapter;
import com.dlwx.firefighting.bean.OrderDetailBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.inter.IntegralGetInter;
import com.dlwx.firefighting.inter.PayPswInter;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.PayPswDialog;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.dlwx.firefighting.utils.glide.GlideImageLoader;
import com.dlwx.firefighting.views.LogisticsDialog;
import com.flyco.dialog.entity.DialogMenuItem;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.dialog.widget.NormalListDialog;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 订单详情页面
 */
public class OrderDetailsActivity extends BaseActivity implements IntegralGetInter {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.order_details_fukuan)
    TextView btnFukuan;
    @BindView(R.id.order_details_cancel)
    TextView btnCancel;
    @BindView(R.id.name_tv)
    TextView nameTv;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.address_tv)
    TextView addressTv;
    @BindView(R.id.recycler)
    LRecyclerView recyclerView;
    @BindView(R.id.express_money_tv)
    TextView expressMoneyTv;
    @BindView(R.id.money_tv)
    TextView moneyTv;

    @BindView(R.id.order_details_rel)
    AutoLinearLayout orderDetailsRel;
    @BindView(R.id.money_ll)
    LinearLayout moneyLl;
    @BindView(R.id.remark_tv)
    TextView remarkTv;
    @BindView(R.id.goods_money_al)
    AutoRelativeLayout goodsMoneyAl;
    @BindView(R.id.ll_logistics)
    LinearLayout llLogistics;
    @BindView(R.id.ll_add)
    LinearLayout llAdd;
    private GlideImageLoader imageLoader;
    private OrderDetailAdapter mAdapter;

    private int payType = Constant.PAY_MONEY;
    private boolean isPayByMoney = true;
    String orderId;
    private String userId;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private HashMap integralMap = new HashMap();
    private boolean isPay = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_details);
        ButterKnife.bind(this);
        orderId = getIntent().getStringExtra("id");
        userId = (String) SPUtils.get(this, Constant.USER_ID, "");
        initView();
        getDatas(orderId);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isPay = (boolean) SPUtils.get(this, Constant.IS_PAY, false);
    }

    private void initView() {
        imageLoader = new GlideImageLoader(this);
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("订单详情");
        mAdapter = new OrderDetailAdapter(this, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter.setDataList(new ArrayList<OrderDetailBean.XiangBean>());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        lRecyclerViewAdapter.removeFooterView();
        lRecyclerViewAdapter.removeHeaderView();
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setLoadMoreEnabled(false);
        recyclerView.setPullRefreshEnabled(false);
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.divider_height)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_gray)
                .build();
        recyclerView.addItemDecoration(divider);
        recyclerView.refresh();

    }

    private void getDatas(String orderId) {
        OkGo.<String>post(Constant.ORDER_DETAIL)
                .tag(this)
                .params("order_id", orderId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult = new DealResult();
//                        List<OrderDetailBean> beans = dealResult.deal(OrderDetailsActivity.this, response, new TypeToken<BaseBean<OrderDetailBean>>() {
//                        }.getType());
//                        setDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(OrderDetailsActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private List<OrderDetailBean.XiangBean> goodsList;

    private void setDatas(List<OrderDetailBean> beans) {
        if (beans.isEmpty()) {
            return;
        }
        OrderDetailBean bean = beans.get(0);

        nameTv.setText("收货人：" + bean.getConsignee());
        addressTv.setText("收货地址：" + bean.getAddress());
        phoneTv.setText(bean.getMobile());
        expressMoneyTv.setText(getString(R.string.rmb) + bean.getShipping_fee());
        moneyTv.setText(getString(R.string.rmb) + bean.getCount_amount());
        goodsList = bean.getXiang();
        isPayByMoney = true;
        setPayType(isPayByMoney);
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @OnClick({R.id.title_left_one_btn, R.id.order_details_fukuan, R.id.order_details_cancel, R.id.ll_logistics,R.id.ll_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                finish();
                break;
            case R.id.order_details_fukuan:
                String str = btnFukuan.getText().toString().trim();
                if (TextUtils.equals(str, "确认收货")) {
                    String content = "确认收货后，不能退货。";
                    final NormalDialog mDiaog = DialogUtils.getNormalDialog(OrderDetailsActivity.this, "提醒", content);
                    mDiaog.setOnBtnClickL(new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mDiaog.dismiss();
                        }
                    }, new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            mDiaog.dismiss();
                            doRece();
                        }
                    });
                } else if (TextUtils.equals(str, "付款")) {
                    Iterator iter = integralMap.entrySet().iterator();
                    while (iter.hasNext()) {
                        Map.Entry entry = (Map.Entry) iter.next();
                        Object key = entry.getKey();
                        Object val = entry.getValue();
                        integralParams = integralParams + key + "," + val + "*";
                    }
                    if (integralParams.endsWith("*")) {
                        integralParams = integralParams.substring(0, integralParams.length() - 1);
                    }
                    doPayPsw();
                } else if (TextUtils.equals(str, "售后服务")) {
                    toAfterSale();
                }
                break;
            case R.id.order_details_cancel:
//                评论
                toComment();
                break;
            case R.id.balance_rb:
                isPayByMoney = true;
                setPayType(isPayByMoney);
                payType = Constant.PAY_MONEY;
                break;
            case R.id.integral_rb:
                integralParams = "";
                isPayByMoney = false;
                setPayType(isPayByMoney);
                payType = Constant.PAY_INTEGRAL;
                break;
            case R.id.ll_logistics:
                LogisticsDialog logisticsDialog = new LogisticsDialog(this);
                logisticsDialog.show();
                break;
            case R.id.ll_add:
                startActivity(new Intent(this,AddressListActivity.class));
                break;
        }
    }


    private void setPayType(boolean isPayByMoney) {
//        balanceRb.setChecked(isPayByMoney);
//        if (isPayByMoney) {
//            integralRb.setChecked(false);
//            moneyLl.setVisibility(View.VISIBLE);
//            remarkTv.setVisibility(View.GONE);
//        } else {
//            integralRb.setChecked(true);
//            moneyLl.setVisibility(View.GONE);
//            remarkTv.setVisibility(View.VISIBLE);
//        }
//        for (OrderDetailBean.XiangBean bean : goodsList) {
//            bean.setPayByMoney(isPayByMoney);
//        }
//        mAdapter.clear();
//        lRecyclerViewAdapter.notifyDataSetChanged();
//        mAdapter.addAll(goodsList);
//        recyclerView.refresh();

    }

    private void toComment() {
        if (goodsList.isEmpty()) {
            return;
        }
        int size = goodsList.size();
        if (size > 1) {
            final ArrayList<DialogMenuItem> mDatas = new ArrayList<>();
            for (OrderDetailBean.XiangBean bean : goodsList) {
                DialogMenuItem item = new DialogMenuItem(bean.getGoods_name(), Integer.parseInt(bean.getRec_id()));
                mDatas.add(item);
            }
            final NormalListDialog mDialog = DialogUtils.getNormalListDialog(this, "选择一个商品", mDatas);
            mDialog.setOnOperItemClickL(new OnOperItemClickL() {
                @Override
                public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mDialog.dismiss();
                    Intent i = new Intent();
                    i.putExtra("bean", goodsList.get(position));
                    i.setClass(OrderDetailsActivity.this, CommentGoodsActivity.class);
                    startActivity(i);
                }
            });
        } else {
            Intent i = new Intent();
            i.putExtra("bean", goodsList.get(0));
            i.setClass(OrderDetailsActivity.this, CommentGoodsActivity.class);
            startActivity(i);
        }
    }


    private void toAfterSale() {
        if (goodsList.isEmpty()) {
            return;
        }
        int size = goodsList.size();
        if (size > 1) {
            final ArrayList<DialogMenuItem> mDatas = new ArrayList<>();
            for (OrderDetailBean.XiangBean bean : goodsList) {
                DialogMenuItem item = new DialogMenuItem(bean.getGoods_name(), Integer.parseInt(bean.getRec_id()));
                mDatas.add(item);
            }
            final NormalListDialog mDialog = DialogUtils.getNormalListDialog(this, "选择一个商品", mDatas);
            mDialog.setOnOperItemClickL(new OnOperItemClickL() {
                @Override
                public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mDialog.dismiss();
                    Intent i = new Intent();
                    i.putExtra("id", mDatas.get(position).mResId + "");
                    i.setClass(OrderDetailsActivity.this, AfterSaleServiceActivity.class);
                    startActivity(i);
                }
            });
        } else {
            Intent i = new Intent();
            i.putExtra("id", goodsList.get(0).getRec_id());
            i.setClass(OrderDetailsActivity.this, AfterSaleServiceActivity.class);
            startActivity(i);
        }
    }

    //输入支付密码
    private void doPayPsw() {
        if (!isPay) {
            final NormalDialog dialog = DialogUtils.getNormalDialog(this, "提示", "设置支付密码");
            dialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    dialog.dismiss();
                }
            }, new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    dialog.dismiss();
                    startActivity(new Intent(OrderDetailsActivity.this, PayPswActivity.class));
                }
            });
            return;
        }
        PayPswDialog mDialog = new PayPswDialog(this, new PayPswInter() {
            @Override
            public void getPsw(String psw) {
                doPay(psw);
            }
        });
        mDialog.show();
    }

    private String integralParams = "";

    private void doPay(String psw) {
        DialogUtils.showProgressDlg(this, "");
        //       积分支付参数（例：1,10*2,20）
        /*PayPswDialog mDialog=new PayPswDialog(this);
        mDialog.show();*/
        OkGo.<String>post(Constant.Pay_ORDER)
                .tag(this)
                .params("user_id", userId)
                .params("orderid", orderId)
                .params("pay_type", payType)
                .params("pay_str", integralParams)
                .params("pay_password", psw)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        integralParams = "";
                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult = new DealResult();
//                        BasicBean basicBean = dealResult.dealBasic(OrderDetailsActivity.this, response);
//                        if (basicBean == null) {
//                            return;
//                        }
//                        PayResBean bean = dealResult.dealOne(OrderDetailsActivity.this, response, new TypeToken<BaseOneBean<PayResBean>>() {
//                        }.getType());
//                        if (bean == null) {
//                            return;
//                        }
//                        ToastUtils.toastForShort(OrderDetailsActivity.this, "支付成功");
//                        Intent i = new Intent(OrderDetailsActivity.this, PayResultActivity.class);
//                        i.putExtra("bean", bean);
//                        startActivity(i);
//                        OrderDetailsActivity.this.finish();

//                        startActivity(new Intent(OrderDetailsActivity.this,UserOrderActivity.class));

                    }

                    @Override
                    public void onError(Response<String> response) {
                        integralParams = "";
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(OrderDetailsActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    //
    private void doRece() {
        DialogUtils.showProgressDlg(this, "");
        OkGo.<String>post(Constant.ORDER_TRUE)
                .tag(this)
                .params("order_id", orderId)
                .params("user_id", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult = new DealResult();
//                        BaseBean bean = dealResult.dealBaseRes(OrderDetailsActivity.this, response);
//                        if (bean == null) {
//                            return;
//                        }
//                        if (bean.getStatus() == Constant.SUCESS) {
//                            btnFukuan.setText("售后服务");
//                        }
//                        ToastUtils.toastForShort(OrderDetailsActivity.this, bean.getMsg());

                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(OrderDetailsActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    String[] mStringItems = {"我不想买了", "信息填写错误，重新拍", "卖家缺货", "同城见面交易", "其他原因"};

    private void cancelOrder() {
        final NormalListDialog dialog = DialogUtils.getNormalListDialogStringArr(OrderDetailsActivity.this, "取消订单", mStringItems);
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.dismiss();
                ToastUtils.toastForLong(OrderDetailsActivity.this, mStringItems[position]);
            }
        });

    }

    /**
     * 获取支付积分参数（goodid,integral*)
     *
     * @param map
     */
    @Override
    public void getIntegral(HashMap map) {
        integralMap = map;
    }

    //--------------------------------------------------------------
}
